//
//  FQDLabOpinionCell.m
//  FakeQDaily
//
//  Created by mewxiv on 9/13/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDLabOpinionCell.h"
#import "UIImage+FQDExtension.h"
#import "UIView+FQDExtension.h"
#import "FQDRestModel.h"

#import "Masonry.h"
#import "UIImageView+WebCache.h"

static CGFloat const kOpinionCellTopSpacing = 10.0f;
static CGFloat const kOpinionAvatarTopSpacing = 10.0f;
static CGFloat const kOpinionAvatarHeight = 25.0f;
static CGFloat const kOpinionContentTopSpacing = 8.0f;
static CGFloat const kOpinionContentPreferredWidth = 125.0f;
static CGFloat const kOpinionContentPreferredHeight = 68.0f;
static CGFloat const kOpinionContentBottomSpacing = 4.5f;
static CGFloat const kOpinionBottomHeight = 32.0f;

@interface FQDLabOpinionCell ()

// 顶部白色边距
@property (nonatomic, strong) UIView *topMarginView;
// 描述图片
@property (nonatomic, strong) UIImageView *descImageView;
// 描述图片遮罩层
@property (nonatomic, strong) UIImageView *descMaskImageView;
// 遮罩底纹
@property (nonatomic, strong) UIImageView *patternImageView;
// 头像
@property (nonatomic, strong) UIImageView *avatarImageView;
// 昵称
@property (nonatomic, strong) UILabel *nameLabel;
// 文字描述
@property (nonatomic, strong) UILabel *descLabel;
// 展开按钮
@property (nonatomic, strong) UIButton *expandButton;
// 点赞按钮
@property (nonatomic, strong) UIButton *praiseButton;
// 分享按钮
@property (nonatomic, strong) UIButton *shareButton;
// 缓存文本是否过长
@property (nonatomic, assign) BOOL contentTooLong;
// 缓存文本是否过短
@property (nonatomic, assign) BOOL contentTooShort;


@end

@implementation FQDLabOpinionCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self prepareUI];
        [self prepareConstraints];
    }
    return self;
}

- (void)prepareUI
{
    self.clipsToBounds = YES;
    _topMarginView = [[UIView alloc] init];
    _topMarginView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:_topMarginView];
    
    _descImageView = [[UIImageView alloc] init];
    _descImageView.contentMode = UIViewContentModeScaleAspectFill;
    _descImageView.clipsToBounds = YES;
    [self.contentView addSubview:_descImageView];
    
    UIImage *descMaskImage = [UIImage imageNamed:@"hud_gradientdeepen_frombottom"];
    _descMaskImageView = [[UIImageView alloc] init];
    _descMaskImageView.image=  descMaskImage;
    _descMaskImageView.contentMode = UIViewContentModeScaleAspectFill;
    _descMaskImageView.clipsToBounds = YES;
    [_descImageView addSubview:_descMaskImageView];
    
    UIImage *patternImage = [UIImage imageNamed:@"mobFeedCellPattern"];
    _patternImageView = [[UIImageView alloc] initWithImage:patternImage];
    _patternImageView.contentMode = UIViewContentModeTopLeft;
    _patternImageView.clipsToBounds = YES;
    [self.contentView addSubview:_patternImageView];
    
    _avatarImageView = [[UIImageView alloc] init];
    _avatarImageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.contentView addSubview:_avatarImageView];
    
    _nameLabel = [[UILabel alloc] init];
    _nameLabel.font = FQDRegularFontWithSize(12.0f);
    _nameLabel.textColor = [UIColor whiteColor];
    _nameLabel.textAlignment = NSTextAlignmentLeft;
    _nameLabel.numberOfLines = 2;
    _nameLabel.preferredMaxLayoutWidth = 475.0f;
    _nameLabel.highlightedTextColor = [UIColor whiteColor];
    [self.contentView addSubview:_nameLabel];
    
    _descLabel = [[UILabel alloc] init];
    _descLabel.font = FQDRegularFontWithSize(14.0f);
    _descLabel.textColor = [UIColor whiteColor];
    _descLabel.textAlignment = NSTextAlignmentLeft;
    _descLabel.numberOfLines = 1;
    _descLabel.preferredMaxLayoutWidth = kOpinionContentPreferredWidth;
    [self.contentView addSubview:_descLabel];
    
    UIImage *expandImage = [UIImage imageNamed:@"mobFlex"];
    _expandButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_expandButton setImage:expandImage forState:UIControlStateNormal];
    [_expandButton addTarget:self action:@selector(expandButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:_expandButton];
    
    NSString *praiseText = @"74 赞";
    UIImage *likeImage = [UIImage imageNamed:@"mobLike"];
    _praiseButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_praiseButton setImage:likeImage forState:UIControlStateNormal];
    [_praiseButton setTitle:praiseText forState:UIControlStateNormal];
    [_praiseButton setImageEdgeInsets:UIEdgeInsetsMake(0, -3, 0, 3)];
    [_praiseButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 3, 0, -3)];
    [_praiseButton setContentEdgeInsets:UIEdgeInsetsMake(0, 3, 0, 3)];
    [_praiseButton addTarget:self action:@selector(praiseOpinion:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:_praiseButton];
    
    _praiseButton.titleLabel.font = FQDRegularFontWithSize(12.0f);
    [_praiseButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    UIImage *shareImage = [UIImage imageNamed:@"mobShare"];
    _shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_shareButton setImage:shareImage forState:UIControlStateNormal];
    [_shareButton addTarget:self action:@selector(shareOpinion:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:_shareButton];
}

- (void)prepareConstraints
{
    WeakSelf;
    
    [_topMarginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.and.left.equalTo(weakSelf.contentView);
        make.width.equalTo(weakSelf.contentView);
        make.height.equalTo(@(kOpinionCellTopSpacing));
    }];

    [_descMaskImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.descImageView);
    }];
    
    [_patternImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.contentView).offset(10);
        make.left.right.and.bottom.equalTo(weakSelf.contentView);
    }];
    
    [_avatarImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.contentView).offset(kOpinionCellTopSpacing + kOpinionAvatarTopSpacing);
        make.left.equalTo(weakSelf.contentView).offset(10);
        make.size.equalTo(@(kOpinionAvatarHeight));
    }];
    
    [_nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.avatarImageView);
        make.left.equalTo(weakSelf.avatarImageView.mas_right).offset(5);
        make.right.equalTo(weakSelf.contentView).offset(-5);
        make.height.greaterThanOrEqualTo(weakSelf.avatarImageView);
    }];
    
    [_expandButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf.contentView);
        make.bottom.equalTo(weakSelf.praiseButton.mas_top).offset(-2);
        make.size.mas_equalTo(CGSizeMake(13, 7));
    }];
    
    [_praiseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.contentView).offset(10);
        make.bottom.equalTo(weakSelf.contentView).offset(-10);
        make.height.equalTo(@16);
    }];
    
    [_shareButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.contentView).offset(-10);
        make.bottom.equalTo(weakSelf.contentView).offset(-12);
        make.size.equalTo(@20);
    }];
}

- (void)configureDescImageView:(FQDLabOpinion *)opinion
{
    if (opinion.image) {
        NSURL *descImageURL = [NSURL URLWithString:opinion.image];
        [self.descImageView sd_setImageWithURL:descImageURL];
    } else {
        self.descImageView.image = nil;
    }
    
    WeakSelf;
    [self.descImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.contentView).offset(10);
        make.left.and.right.equalTo(weakSelf.contentView);
        make.height.equalTo(weakSelf.contentView.mas_width).multipliedBy(0.5);
    }];
}

- (void)configureDescLabel:(FQDLabOpinion *)opinion
{
    BOOL contentTooLong = self.contentTooLong;
    BOOL contentTooShort = self.contentTooShort;
    BOOL hasImage = ([opinion.image length] > 0);
     if (hasImage) {
        self.descLabel.numberOfLines = 1;
        self.descLabel.textAlignment = NSTextAlignmentLeft;
        self.descLabel.font = FQDRegularFontWithSize(14.0f);
    } else if (contentTooLong) {
        self.descLabel.numberOfLines = 3;
        self.descLabel.textAlignment = NSTextAlignmentLeft;
        self.descLabel.font = FQDRegularFontWithSize(14.0f);
    } else {
        self.descLabel.numberOfLines = 0;
        self.descLabel.textAlignment = NSTextAlignmentCenter;
        CGFloat fontSize = (contentTooShort) ? 21.0f : 14.0f;
        self.descLabel.font = FQDRegularFontWithSize(fontSize);
    }
    
    WeakSelf;
    UIImageView *anchorImageView = (hasImage) ? self.descImageView : self.avatarImageView;
    [self.descLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(anchorImageView.mas_bottom).offset(8);
        make.left.equalTo(weakSelf.contentView).offset(10);
        make.right.equalTo(weakSelf.contentView).offset(-10);
        
        if (!hasImage && !contentTooLong) {
            make.bottom.equalTo(weakSelf.praiseButton.mas_top).offset(-8);
        }
    }];
}

- (void)expandCell:(BOOL)animated
{
    WeakSelf;
    
    self.expandButton.hidden = YES;
    self.descLabel.numberOfLines = 0;
    [self.descImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.contentView).offset(10);
        make.left.and.right.equalTo(weakSelf.contentView);
        make.height.equalTo(weakSelf.contentView.mas_width);
    }];
    
    if (animated) {
        UIImage *snapshot = [self captureViewHierarchy];
        UIImageView *snapshotView = [[UIImageView alloc] initWithImage:snapshot];
        snapshotView.frame = self.bounds;
        [self.contentView addSubview:snapshotView];
        [UIView animateWithDuration:0.3 animations:^{
            snapshotView.alpha = 0;
        } completion:^(BOOL finished) {
            [snapshotView removeFromSuperview];
        }];
    }
}


#pragma mark - Event response
- (void)expandButtonClicked:(id)sender
{
    [self expandCell:YES];
    if ([self.delegate respondsToSelector:@selector(collectionViewCell:actionType:actionControl:userInfo:)]) {
        [self.delegate collectionViewCell:self actionType:FQDLabOpinionCellActionClickExpandButton
                            actionControl:sender userInfo:nil];
    }
}

- (void)praiseOpinion:(id)sender
{
    
}

- (void)shareOpinion:(id)sender
{
    
}

#pragma mark - Getters and Setters
- (void)setOpinion:(FQDLabOpinion *)opinion
{
    _opinion = opinion;
    self.descLabel.text = opinion.content;
    self.nameLabel.text = opinion.author.name;
    
    NSURL *avatarURL = [NSURL URLWithString:opinion.author.avatar];
    [[SDWebImageManager sharedManager] downloadImageWithURL:avatarURL options:0 progress:nil
     completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
         self.avatarImageView.image = [image roundImage];
    }];
    
    CGFloat preferredWidth = self.descLabel.preferredMaxLayoutWidth;
    NSDictionary *attrs = @{ NSFontAttributeName : self.descLabel.font };
    CGSize contentTextSize = [opinion.content boundingRectWithSize:CGSizeMake(preferredWidth, CGFLOAT_MAX)
                       options:NSStringDrawingUsesLineFragmentOrigin
                       attributes:attrs
                       context:nil].size;
    self.contentTooLong = (contentTextSize.height > kOpinionContentPreferredHeight);
    self.contentTooShort = ([opinion.content length] < 10);
    
    [self configureDescImageView:opinion];
    [self configureDescLabel:opinion];
    
    if (self.contentTooLong || ([opinion.image length] > 0)) {
        self.expandButton.hidden = NO;
    } else {
        self.expandButton.hidden = YES;
    }
  
}

- (void)setColorIndex:(NSInteger)colorIndex
{
    _colorIndex = colorIndex;
    
    static NSArray *colorList;
    if (!colorList) {
        colorList = @[
            RGB(143, 130, 188),
            RGB(242, 156, 159),
            RGB(53, 189, 199),
            RGB(255, 161, 46),
            RGB(230, 90, 79),
            RGB(161, 193, 92),
            RGB(118, 203, 162),
        ];
    }
    
    self.backgroundColor = colorList[colorIndex % [colorList count]];
}

+ (CGFloat)heightForOpinion:(FQDLabOpinion *)opinion fittingWidth:(CGFloat)fitWidth
{
    NSString *content = opinion.content;
    CGFloat preferredWidth = kOpinionContentPreferredWidth;
    NSDictionary *attrs = @{ NSFontAttributeName : FQDRegularFontWithSize(14.0f) };
    CGSize contentTextSize = [content boundingRectWithSize:CGSizeMake(preferredWidth, CGFLOAT_MAX)
                          options:NSStringDrawingUsesLineFragmentOrigin
                          attributes:attrs
                          context:nil].size;
    
    CGFloat cellHeight = kOpinionCellTopSpacing;
    if ([opinion.image length] > 0) {
        cellHeight += fitWidth;
    } else {
        cellHeight += kOpinionAvatarTopSpacing + kOpinionAvatarHeight;
    }
    cellHeight += kOpinionContentTopSpacing + contentTextSize.height;
    cellHeight += kOpinionContentBottomSpacing + kOpinionBottomHeight;
    
    
    return cellHeight;
}

+ (NSString *)reuseId
{
    return @"FQDLabOpinionCell";
}

@end
